package cn.codesugar.data.storage

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import cn.codesugar.data.storage.databinding.ActivityFileBinding
import java.io.*

class FilePersistenceTestActivity : AppCompatActivity() {

    private var b: ActivityFileBinding? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        b = ActivityFileBinding.inflate(layoutInflater)
        setContentView(b?.root)
        val inputText = load()
        if (inputText.isNotEmpty()) {
            b?.editText?.setText(inputText)
            b?.editText?.setSelection(inputText.length)
            Toast.makeText(this, "Restoring succeeded", Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 写入内容到文件中
     * <p>
     *     Context.MODE_PRIVATE 覆盖原来的文件
     *     Context.MODE_APPEND 该文件已存在，就往文件里面追加内容，不存在就创建新文件
     * </p>
     */
    private fun save(inputText: String) {
        try {
            val output = openFileOutput("data", Context.MODE_PRIVATE)
            val writer = BufferedWriter(OutputStreamWriter(output))
            writer.use {
                it.write(inputText)
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    /**
     * 读取文件
     */
    private fun load(): String {
        val content = StringBuilder()
                try {
                    val input = openFileInput("data")
                    val reader = BufferedReader(InputStreamReader(input))
                    reader.use {
                        reader.forEachLine {
                            content.append(it)
                        }
                    }
                } catch (e: IOException) {
                    e.printStackTrace()
                }
        return content.toString()
    }

    override fun onDestroy() {
        super.onDestroy()
        val inputText = b?.editText?.text.toString()
        save(inputText)
    }

}